package com.hjq.fcloud.utils

import com.hjq.fcloud.bean.CommonFileBean
import com.hjq.fcloud.bean.FileItemBean
import com.obs.services.ObsClient
import com.obs.services.exception.ObsException
import com.obs.services.model.PutObjectResult
import java.io.File

/**
 * 华为Obs文件上传
 */
object HuaweiObsUtils {

    private val END_POINT = "obs.cn-southwest-2.myhuaweicloud.com"
    private val BUCKET_NAME = "dgfcloud-obs"
    private val AK = "RYNO0YKPRHBN0EVECO5V"
    private val SK = "wEeCsexVgaO8KJVH7QkuVfugiKJN2w18qqrawvp3"

    //各个目录，好区分
    val DIR_FACE = "face"
    val DIR_SIGN = "sign"
    val DIR_IMAGE = "image"
    val DIR_VIDEO = "video"
    val DIR_FILE = "file"

    fun uploadFile(
        itemBean: CommonFileBean,
        dir: String? = DIR_FILE,
        bucketName: String? = BUCKET_NAME,
    ):CommonFileBean {
        // 认证用的ak和sk硬编码到代码中或者明文存储都有很大的安全风险，建议在配置文件或者环境变量中密文存放，使用时解密，确保安全；本示例以ak和sk保存在环境变量中为例，运行本示例前请先在本地环境中设置环境变量ACCESS_KEY_ID和SECRET_ACCESS_KEY_ID。
        // 您可以登录访问管理控制台获取访问密钥AK/SK，获取方式请参见https://support.huaweicloud.com/usermanual-ca/ca_01_0003.html
        val ak = AK
        val sk = SK
        val endPoint = END_POINT
        // 创建ObsClient实例
        val obsClient = ObsClient(ak, sk, endPoint)
        try {
            // localfile为待上传的本地文件路径，需要指定到具体的文件名
            var filePath = itemBean.url
            var fileName = FileUtils.getFileName(filePath)
            var objectKey = "fcloud/web/app/$dir/" + fileName
            var result = obsClient.putObject(
                BUCKET_NAME,
                objectKey,
                File(filePath)
            )
            var objectUrl = getRealFileUrl(result)
            Logger.i("--->>>HuaweiObsUtils uploadFile success objectUrl:" + objectUrl)
            itemBean.uploasSuccess = true
            itemBean.url = objectUrl
            return itemBean
        } catch (e: ObsException) {
            e.printStackTrace()
            var errorCode = e.errorCode
            var errorMessage = e.errorMessage
            Logger.i("--->>>HuaweiObsUtils uploadFile fail errorCode:" + errorCode + ",errorMessage:" + errorMessage)
            return itemBean
        } finally {
            obsClient.close()
        }
    }

    /**
     * url换成我们绑定的域名，图片和视频可以直接浏览器打开
     */
    private fun getRealFileUrl(result: PutObjectResult): String {
        var objectUrl = result.objectUrl
        var replaceUrl = "https://dgfcloud-obs.obs.cn-southwest-2.myhuaweicloud.com:443"
        if (objectUrl.startsWith(replaceUrl)) {
            objectUrl = objectUrl.replace(replaceUrl, "https://file.lsdgjs.com")
        }
        return objectUrl
    }
}

class HuaweiObsResult{
    var success:Boolean = false
    var url:String = ""
    var obsException:ObsException? = null
}